package com.lmq.wxshare.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lmq.wxshare.common.HttpRequest;
import com.lmq.wxshare.entity.Produce;
import com.lmq.wxshare.entity.User;
import com.lmq.wxshare.mapper.ProduceMapper;
import com.lmq.wxshare.mapper.UserMapper;
import com.lmq.wxshare.service.ProduceService;
import com.lmq.wxshare.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Value("${wx.userMsgUrl}")
    private String USER_MSG_URL;

    @Override
    public User insertOrUpdateByJson(String json) {
        JSONObject userjson = JSONObject.parseObject(json);
        String openid = userjson.getString("openid");
        if(StringUtils.isBlank(openid)){
            return null;
        }
        User user = baseMapper.getUserByOpenid(openid);
        if(user!=null){
            user.setAccessToken(userjson.getString("access_token"));
            user.setRefreshToken(userjson.getString("refresh_token"));
            user.setScope(userjson.getString("scope"));
            baseMapper.update(user, null);
        }else{
            user = new User();
            user.setOpenId(openid);
            user.setAccessToken(userjson.getString("access_token"));
            user.setRefreshToken(userjson.getString("refresh_token"));
            user.setScope(userjson.getString("scope"));
            baseMapper.insert(user);
        }
        return user;
    }

    @Override
    public User getUserDetail(User user) {
        String userMsgUrl = USER_MSG_URL;
        userMsgUrl = userMsgUrl.replace("ACCESS_TOKEN", user.getAccessToken()).replace("OPENID", user.getOpenId());
        String result = HttpRequest.sendGet(userMsgUrl, null);
        JSONObject userjson = JSONObject.parseObject(result);
        user.setNikeName(userjson.getString("nickname"));
        user.setSex(userjson.getInteger("sex"));
        user.setProvince(userjson.getString("province"));
        user.setCity(userjson.getString("city"));
        user.setCountry(userjson.getString("country"));
        user.setHeadimgUrl(userjson.getString("headimgurl"));
        user.setPrivilege(userjson.getString("privilege"));
        user.setUnionid(userjson.getString("unionid"));
        return user;
    }
}
